<?php 

session_start();

class Vital{
	public $id;
	public $conteudo;
	public $tabela;
	public $titulo;
	public $campos;
	public $elementos;
	public $usuario;
	public $ordem;
	public $disableDB=false;
	public $busca;
	public $pagina;
	public $acaoTabela;
	public $str_form;
	public $privilegio;
	public $error;
	public $editar_grid;
	public $texto_msg;
	public $tipo_msg;
	public $form_pag;
	
	function Vital(){
		$file=explode(".",basename($_SERVER["SCRIPT_NAME"]));
		//$this->auth();
		$this->campos=array("tb.id"=>"id");
		if(!$_SESSION["usuario"]&&$file[0]!="login"){
			$url = urlencode("http://".$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]);
			//$url=($_GET["url"])?$_GET["url"]:"http://$url";
			//die(BASE);
			//header("Location: ".BASE."/sair.php?url=$url");
			//header("Location: ".BASE."/sair.php");
		}
	}
	
	static function auth($usuario=null){
		if($usuario){
			$_SESSION["usuario"]=$usuario;
			//print_r($_SESSION["usuario"]);die;
		}
	}
	
	static function verificaAuth(){
		$file=explode(".",basename($_SERVER["SCRIPT_NAME"]));
		
		if(!$_SESSION["usuario"]&&$file[0]!="login"){
			$url = urlencode($_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]);
			header("Location: ".BASE."/login.php");
		}
	}
	
	static function mensagem($str){
		
	}
	
	function setTabela($tabela){
		define("TABELA",$tabela);
		$this->tabela=$tabela;
	}
	
	function setCampos($campos){
		$this->campos+=$campos;
	}
	
	function setOrdem($ordem){
		$this->ordem=$ordem;
	}
	
	function setTitulo($titulo){
		$this->titulo=$titulo;
	}
	
	function setPagina($pagina){
		define("PAGINA",$pagina);
		$this->pagina=$pagina;
	}
	
	function assign($busca,$valor){
		$this->conteudo=str_replace('{'.$busca.'}', $valor, $this->conteudo);
	}
	
	function parseArrayToObject($array) {
	    $object = new stdClass();
	    if (is_array($array) && count($array) > 0) {
	        foreach ($array as $name=>$value) {
	            $name = strtolower(trim($name));
	            if (!empty($name)) {
	                $object->$name = $value;
	            }
	        }
	    }
	    return $object;
	}
	
	function display($form=null,$dados=null){
		
		foreach ($this->busca as $ide => $label){
			if($ide==$_POST["campo"]):
				$opt.="<option selected='selected' value='$ide'>$label</option>";
			else:
				$opt.="<option value='$ide'>$label</option>";
			endif;
		}
		
		/**
		 * POST
		 */
			
		$this->form_pag=$form;
			
			/**
			 * Verifica se os campos sao
			 * requeridos.
			 */
			if(!$this->disableDB){
				if($dados){ 
					$form->montar(($_POST)?$_POST:$dados);
				}else{
				}
			}
			
			foreach ($_POST as $k=>$v){
				//echo($v."asda");
				if($form->required[$k]&&!$v){
					$this->texto_msg.="Preencha: ".$form->required[$k]."<br />";
					$this->tipo_msg="error";
					$this->error=true;
					
					$dados=$_POST;
				}
				
			}
			
			foreach($_POST["excluir_arquivo"] as $ke => $e){
				//DB::apagar("arquivo='$ke'","anexos");
				DB::atualizar(array("arquivo"=>''),"arquivo='$ke'",$this->tabela);
			}
			
			for($i=0;$i<sizeof($form->elementos);$i++){
				$class='';
				if($form->elementos[$i]["left"]){
					$class="left";
				}
				if($obj=$form->elementos[$i]["multi"][0]){
					$nome_elm=$form->elementos[$i]["nome"];
					$titulo_elm=$form->elementos[$i]["titulo"];
					//$cont=1;
					$string_elementos.="<p><h2 style='margin-bottom: 0;'>Anexos - <input type='file' name='{$nome_elm}[$nome_elm]' /></h2></p>";
					
					foreach(DB::fetchTodos("*","anexos","id_tarefa={$dados['id']}") as $v){
						$el= $form->setArquivo("{
								'nome'   : 'arquivo',
								'titulo' : 'Arquivo',
								'return_elemento' : 'true',
								'multi'  : [{'tabela':'anexos'}],
								'valor'  : '{$v['arquivo']}'}");
						
						$bkg=($cont%2==0)?"#EAEAEA":"white";
						
						/**
						 * <p>
									<label>Small form input</label>
										<input class="text-input small-input" type="text" id="small-input" name="small-input" /> <span class="input-notification success png_bg">Successful message</span> <!-- Classes for input-notification: success, error, information, attention -->
										<br /><small>A small description of the field</small>
								</p>
						 * @var unknown_type
						 */
						
						$string_elementos.="<li style='background: $bkg;padding-left: 10px;color: gray;'>$el {$v['usuario']}-{$v['data']}</li>";
						$cont++;
					}
					
					//$string_elementos.="<li><div>Anexo</div><input type='file' name='{$nome_elm}[$nome_elm]' /></li>";
				}else{
						$string_elementos.="<p>{$form->elementos[$i]["elemento"]}</p>";
				}
			}
			//die(print_r($form->elementos)."sdfs");
			
			$action=($_GET["acao"]!="editar")?"novo":"editar";
			$action=BASE."/".$this->tabela.".php?acao=$action";
			$this->str_form="
			<fieldset>
				<form action='$action' method='post' enctype='multipart/form-data' >
					$string_elementos
					<p>
					<input type='reset' class='button' value='Limpar' />
					<input type='submit' class='button' value='Salvar' />
					</p>
				</form>
			</fieldset>";
			
			/*
			 * Atualiza/Salva o Formulario.
			 */
			if(!$this->disableDB){
				if($_POST){
					$cont=0;
					foreach($_FILES as $k){
						$key = key($k['name']);
						if($k['name'][$key]){
							$dados[$key]=Form::upload($k['name'][$key],$k['tmp_name'][$key],"uploads");
							$_POST[$key]=$dados[$key];
						}
						if($_POST["excluir_arquivo"][$key]){
							//die($key);
							$dados[$key]='';
							$_POST[$key]='';
						}
						$cont++;
					}
				}
				if($_POST && !$_POST["id"] && !$this->error){
					$this->texto_msg="Salvo com sucesso.";
					$this->tipo_msg="success";
					$return_id = DB::salvar(($_POST)?$_POST:$dados,$this->tabela,$form->elementos);
				}elseif($id=$_POST["id"] && !$this->error && $_POST){
					$this->texto_msg="Alterado com sucesso.";
					$this->tipo_msg="success";
					(!$dados)?$dados=$_POST:null;
					DB::atualizar($_POST,"id={$_POST["id"]}",$this->tabela);
				}
			}
			
			$o=$_SESSION["usuario"];
			
			/**
			 * Listar
			 */
			
			$pagina=(!$_GET["pagina"])?0:$_GET["pagina"];
			$registros_pagina=10;
			
			//$pagina_anterior=round($registros_pagina*$pagina);
			//$pagina_proxima=round(($registros_pagina*$pagina)+$registros_pagina);
			$pagina_anterior=$pagina*$registros_pagina;
			
			if(!$pagina)
				$pagina_anterior=0;
				
			$limite=$pagina_anterior.",".$registros_pagina;
			
			//die($limite);
			$tc=round(820/(sizeof($this->campos)-1))."px";
			
			foreach ($this->campos as $id=>$c){
				$width=($c=="id")?"width:50px":"width:$tc";
				
				if($c=="id")
					continue;
				
				if($c[3]&&is_array($c)){
					$id_m=$c[3];
				}else{
					$id_m=strtolower($id);
				}
				if(is_array($c))$c=$id;
				$pagina=($this->pagina)?$this->pagina:$this->tabela;
				$titulo.="<th style='text-align: left;'>
					<a style='' href='{$pagina}.php?ordem=$id_m'>$c</a></th>";
			}
			
			if($_POST){
				$where="{$_POST['campo']} like '%{$_POST['busca']}%'";
			}
			
			//permissao
			if($this->tabela=="usuarios" && $o['grupo']!=1){
				//($where)?$where.=" AND ":null;
				//$where.="empresa = '{$o['empresa']}'";
				
				if($o["grupo"]==2){
					//($where)?$where.=" AND ":null;
					//$where.=" grupo <> 1 ";
				}
				
			}elseif($this->tabela=="projetos"){
				($where)?$where.=" AND ":null;
				$where.="empresa = '{$o['empresa']}'";
			}
			
			if($this->pagina=="minhas-tarefas"){
				($where)?$where.=" AND ":null;
				$where.="tb.responsavel = '{$o['id']}'";
				$where.=" AND ativo <> 2 ";
			}
			
			if($this->pagina=="tarefas-criadas"){
				($where)?$where.=" AND ":null;
				$where.="tb.usuario = '{$o['id']}'";
				$where.=" AND ativo <> 2 ";
			}
			
			if($this->tabela=="tarefas"){
				($where)?$where.=" AND ":null;
				$where.=" tb.ativo=1 ";
				($where)?$where.=" AND ":null;
				$where.=" tb.status<>100 ";
				
				if($o["grupo"]!=1){
					($where)?$where.=" AND ":null;
					$where.=" tb.empresa={$o['empresa']} ";
				}
				
				//$where.=" tb.responsavel = '{$o['id']}' ";
			}
			
			if($ordem=$_GET["ordem"]){
				$this->ordem="$ordem, ";
			}
			$this->ordem.=" tb.ordem ";
			if($ordem=="status"){
				$this->ordem.=" DESC";
			}else{
				$this->ordem.=" ASC";
			}
			
				//die($where);
			$limite=null;
			
			$lista=DB::lista($this->campos,$this->tabela,$where,$limite,$this->ordem);
			
			foreach ($lista as $v){
				foreach ($this->campos as $idc=>$c){
					
					if($c=="id")
						continue;
						
					$input_elm='';
					if(is_array($c)){
						$alias=($c[3])?$c[3]:null;
						if(!$alias){
							$alias=$c[2];
						}
						
						$aalias=explode(".",$alias);
						if($aalias[1]){
							$alias=$aalias[1];
						}
						$valor=$v[$alias];
					}else{
						$arrz=explode(".",$idc);
						
						if($arrz[1]){
							$arrz=$arrz[1];
						}else{
							$arrz=$idc;
						}
						
						if($c=="id")
							$valor=$v[$c];
						else
							$valor=$v[$arrz];
						
					}
					$width=($c=="id")?"width:50px;":"width:$tc";
						//echo $idc;
					if($this->editar_grid[$idc] && $c!="id"){
						$type=(is_array($this->editar_grid[$idc]))?"select":"text";
						
						switch ($type){
							case 'text':$input_elm="<input type='$type' onblur='editar_ajax(this);' id='{$idc}_{$v["id"]}'
									style='display: none;' alt='{$v["id"]}' title='$idc'
									name='{$this->editar_grid[$idc]}' value='{$valor}' />";
									break;
							case "select":$input_elm="<select onchange='editar_ajax(this);' id='{$idc}_{$v["id"]}'
									style='display: none;' alt='{$v["id"]}' title='{$this->editar_grid[$idc]["campo_tabela"]}'
									name='{$this->editar_grid[$idc]['tabela_salvar']}' rel='select'>";
									
									$input_elm.="<option value=''>Selecione</option>";
									foreach(DB::fetchTodos("*",$this->editar_grid[$idc]["tabela"]) as $e){
										$input_elm.="<option value='{$e["id"]}'>{$e[$this->editar_grid[$idc]["campo"]]}</option>";
									}
									$input_elm.="</select>";
									break;
						}
					}
					
					$cont.="<td nowrap='nowrap' class=''>
								<span onclick=".'"'."abrir_editar('{$idc}_{$v["id"]}')".'"'." id='span_{$idc}_{$v["id"]}'>
									{$valor}
								</span>
								$input_elm	
							</td>";
				}
				
				$tr.='<tr id="'.$this->tabela."_".$v["id"].'">
						'.$cont.'
						<td nowrap="nowrap" style="text-align: right;">
			                &nbsp;
			                ';
				if(!$this->privilegio["excluir"]){
					$str="<img src='images/icons/cross.png' />";
					$link_editar="<a href='".$this->tabela.".php?acao=editar&id=".$v["id"]."'"."><img src='images/icons/pencil.png' al='Editar' />";
					
					$link="{$this->tabela}.php?acao=apagar&id={$v["id"]}";
					
					if($this->tabela!="textos"){
						$ahref='&nbsp;<a onclick="if(confirm('."'Deseja excluir?'"."))window.open('$link','_self');".'"'.' href="javascript:;">'.$str;
					}
					
					$tr.="$link_editar $ahref</a>";
				}
						
				$tr.='</td>
					</tr>';
				$cont="";
			}
			
			$tabela="<table class='table' style='width: 100%;'><thead><tr>$titulo<th></th></tr></thead><tbody>$tr</tbody></table>";
			$this->conteudo=$tabela;
		
		$this->conteudo=str_replace("{opt_campo}", $opt, $this->conteudo);
		$this->conteudo=str_replace("{base_url}", $this->tabela, $this->conteudo);
		
		foreach(Menu::get() as $k => $v){
			$pagina=($this->pagina)?$this->pagina:$this->tabela;

			$class=($k==$pagina)?"class='active'":"";
			$menu.="<li><a $class href='{$k}.php'>{$v}</a></li>";
		}
		
		$this->conteudo=str_replace("{template.menu}","<div class='menu-top clearfix'><ul>".$menu."</ul></div>",$this->conteudo);
		$this->conteudo=str_replace("{chat}", file_get_contents("chat.php"), $this->conteudo);
		
		return $return_id;
	}
	
	function show(){
		if($this->error){
		}else{
			($_POST)?header("Location: {$this->tabela}.php?msg=1"):null;
		}
		
		//echo preg_replace('[{.*}]', '', $this->conteudo);
		if(!$this->privilegio["novo"])
			$novo='<a style="float: right;" href="'.$this->tabela.'.php?acao=novo" class="noticia-new new"><img src="images/novo.png" />Adicionar novo</a>';
		
		$conteudo = $this->conteudo;
		$titulo   = $this->titulo;
		$str_form   = $this->str_form;
		
		$this->form_pag->elementos=array();
		$this->form_pag->montar();
		
		for($i=0;$i<sizeof($this->form_pag->elementos);$i++){
			$novo_formulario.="<p>".$this->form_pag->elementos[$i]["elemento"]."</p>";
		}
		
		$action=BASE."/".$this->tabela.".php?acao=novo";
		$novo_formulario="
		<fieldset>
			<form action='$action' method='post' enctype='multipart/form-data' >
				$novo_formulario
				<p>
				<input type='reset' class='button' value='Limpar' />
				<input type='submit' class='button' value='Salvar' />
				</p>
			</form>
		</fieldset>";
		
		if($_GET["acao"]){
			$conteudo=$str_form;
		}
		
		if($_GET["acao"]=='apagar'){
			header("Location: {$this->tabela}.php");
		}
		
		//($_GET['nolayout'])?require_once("config.php"):null;
		//($_GET['nolayout'])?print($conteudo):null;
		
		$texto_msg=$this->texto_msg;
		$tipo_msg=$this->tipo_msg;
		
		(!$_GET['nolayout'])?require_once("templates/cabecalho.php"):null;
		(!$_GET['nolayout'])?require_once "templates/layout.php":null;
		(!$_GET['nolayout'])?require_once "templates/rodape.php":null;
	}
}

?>